package com.yang.net.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;


/**
 * @author yds
 * @program net-sokect_stduy
 * @description 作为项目过滤器
 * @create 2020-09-27 09:27
 **/
@WebFilter(filterName = "NetFilter", urlPatterns = { "/localhost" })
public class NetFilter extends HttpServlet implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)res;
        String requestHost=request.getHeader("host");
        //host非空  未通过白名单则禁止访问
        if(null != requestHost&&!"".equals(requestHost)&&!checkWhiteList(requestHost)){
            response.setStatus(403);//
            return;
        }
        chain.doFilter(req, res);//放行
    }

    /**
     * 验证白名单
     * @return true  验证通过 在白名单中
     * @return false 验证未通过 不在白名单中
     */
    private  boolean checkWhiteList(String host){
        if(host.contains("/localhost")){
            return true;
        }
        return false;
    }

    public void init(FilterConfig arg0) throws ServletException {

    }



}